package mqtt.simple.demo2;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class TestMqttPublishBroker {
    /**
     * 代理服务器ip地址
     */
    public static final String MQTT_BROKER_HOST = "tcp://127.0.0.1:1889";
    /**
     * 客户端唯一标识
     */
    public static final String MQTT_CLIENT_ID = "1678415541515";
    /**
     * 订阅标识
     */
    public static final String MQTT_TOPIC = "test2";
    private static String USERNAME = "1740319256418201601";
    private static String PASSWORD = "3CD881BDA6BC2F9D0FA2398380ADC1DF";

    private volatile static MqttClient mqttClient;
    private static MqttConnectOptions options;

    public static void main(String... args) throws MqttException {
        try {
            // host为主机名，clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，
            // MemoryPersistence设置clientid的保存形式，默认为以内存保存

            mqttClient = new MqttClient(MQTT_BROKER_HOST, MQTT_CLIENT_ID, new MemoryPersistence());
            // 配置参数信息
            options = new MqttConnectOptions();
            // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，
            // 这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            // 设置用户名
            options.setUserName(USERNAME);
            // 设置密码
            options.setPassword(PASSWORD.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(1);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(30);
            // 连接
            mqttClient.connect(options);

            long begin = System.currentTimeMillis();
//            MqttMessage message = new MqttMessage("content".getBytes());
            String message = "{\"health\":\"1\"}";

            for (int i = 0; i < 20; i++) {
                try {
                    mqttClient.publish("/sys/1_6f7122ecefa/1740319256418201601/thing/post", message.getBytes(), 0, false);
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(System.currentTimeMillis() - begin);

            // 订阅
//            mqttClient.subscribe(MQTT_TOPIC);
            // 设置回调
            mqttClient.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable throwable) {
                    System.out.println("connectionLost");
                }

                @Override
                public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                    System.out.println("Topic: " + s + " Message: " + mqttMessage.toString());
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        mqttClient.disconnect();
    }

}
